<template>
  <div class="userIndex">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- card卡片 -->
<el-card class="box-card">
   <!-- 输入框 -->
  <div class="text item" :span="12">
    <el-row :gutter="20">
  <el-col :span="8">
    <!-- clearable	是否可清空	boolean	—	false
         clear	在点击由 clearable 属性生成的清空按钮时触发
    -->
    <el-input @change="OnChange" clearable @clear="empty" placeholder="请输入内容" v-model="paramData.query">
    <el-button @click="clickSearchBtn" slot="append" icon="el-icon-search"></el-button>
  </el-input>
  </el-col>
  <el-col :span="6">
    <el-button @click="addUsers" type="primary" :span="12">添加用户</el-button>
  </el-col>
</el-row>
 <el-table
    :data="userListData"
    border
    stripe
    style="width: 100%">
     <el-table-column
      type="index"
      width="50">
    </el-table-column>
    <el-table-column
      prop="username"
      label="姓名"
        >
    </el-table-column>
    <el-table-column
      prop="email"
      label="邮箱"
        >
    </el-table-column>
    <el-table-column
      prop="mobile"
      label="电话"
        >
    </el-table-column>
    <el-table-column
      prop="role_name"
      label="角色"
        >
    </el-table-column>
    <el-table-column
      prop="mg_state"
      label="状态"
        >
         <template slot-scope="scope">
           <div>
             <!-- {{scope.row}} -->
             <el-switch
             v-model="scope.row.mg_state"
            @change="stateMonitor(scope.row)"
            >
             </el-switch>
           </div>
         </template>
    </el-table-column>
    <el-table-column
      label="操作"
      width="180px"
        >
        <template slot-scope="scope">
          <div class="tableBtn">
            <!-- 修改用户按钮 -->
            <el-button @click="amendUsers(scope.row.id)" type="primary" size="mini" icon="el-icon-edit"></el-button>
            <!-- 删除用户按钮 -->
            <el-button @click="deleteUser(scope.row.id)" type="danger" size="mini" icon="el-icon-delete"></el-button>
             <el-tooltip effect="dark" content="分配角色" :enterable="false" placement="top-start">
      <el-button @click="assignRoles(scope.row)" type="warning" size="mini" icon="el-icon-share"></el-button>
    </el-tooltip>

          </div>
        </template>
    </el-table-column>

  </el-table>
  </div>
  <!-- 分页 -->
  <div class="paging">
    <!--
    size-change	pageSize 改变时会触发	每页条数
    current-change	currentPage 改变时会触发	当前页
     current-page	当前页数，支持 .sync 修饰符	number	—	1
     page-sizes	每页显示个数选择器的选项设置	number[]	—	[10, 20, 30, 40, 50, 100]
     layout	组件布局，子组件名用逗号分隔	String	sizes, prev, pager, next, jumper, ->, total, slot	'prev, pager, next, jumper, ->, total'
     total	总条目数	number	—	—
     -->
    <el-pagination
      @size-change="newSizeChange"
      @current-change="newCurrentChange"
      :current-page="paramData.pagenum"
      :page-sizes="[1, 2, 3, 5,10]"
      :page-size="paramData.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</el-card>
  <!-- 添加用户弹框 -->
  <el-dialog
  title="添加用户"
  :visible.sync="AddDialogVisible"
  width="50%"
  >
  <div>
     <!-- 用户名 -->
  <el-form
  :model="addruleForm"
  :rules="rules"
   ref="addruleRef"
   label-width="100px"
   >
   <!-- 姓名 -->
  <el-form-item label="姓名" prop="username">
    <el-input v-model="addruleForm.username"></el-input>
  </el-form-item>
   <!-- 密码 -->
   <el-form-item label="密码" prop="password">
    <el-input v-model="addruleForm.password"></el-input>
  </el-form-item>
  <!-- 邮箱 -->
   <el-form-item label="邮箱" prop="email">
    <el-input v-model="addruleForm.email"></el-input>
  </el-form-item>
  <!-- 电话 -->
   <el-form-item label="电话" prop="mobile">
    <el-input v-model="addruleForm.mobile"></el-input>
  </el-form-item>
  </el-form>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="addUserList">确 定</el-button>
    <el-button @click="AddDialogVisible = false">取 消</el-button>
    <el-button @click="resetForm('addruleForm')">重置</el-button>
  </span>
</el-dialog>
<!-- 修改用户弹框 -->
  <el-dialog
  title="修改用户"
  :visible.sync="amendruleForm"
  width="50%"
  >
  <div>
     <!-- 用户名 -->
  <el-form
  :model="amenUsers"
  :rules="amendrules"
   ref="amendruleRef"
   label-width="100px"
   >
   <!-- 姓名 -->
  <el-form-item label="姓名" prop="username">
    <el-input v-model="amenUsers.username" disabled></el-input>
  </el-form-item>
  <!-- 邮箱 -->
   <el-form-item label="邮箱" prop="email">
    <el-input v-model="amenUsers.email"></el-input>
  </el-form-item>
  <!-- 电话 -->
   <el-form-item label="电话" prop="mobile">
    <el-input v-model="amenUsers.mobile"></el-input>
  </el-form-item>
  </el-form>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="amenUserList">确 定</el-button>
    <el-button @click="amendruleForm = false">取 消</el-button>
    <el-button @click="resetForm('addruleForm')">重置</el-button>
  </span>
</el-dialog>
<!-- 分配角色 -->
<el-dialog
  title="分配角色"
  :visible.sync="allocateRolesVisible"
  width="50%"
  >
<div>
  <p>当前用户：{{configInfo.username}}</p>
  <p>当前用户角色：{{configInfo.role_name}}</p>
    <p>分配新角色：
      <el-select v-model="assignNewRoles" placeholder="请选择">
          <el-option
          v-for="item in assignRolesData"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
        </el-option>
  </el-select>
  </p>
</div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="allocateRolesVisible = false">取 消</el-button>
    <el-button type="primary" @click="selectOption">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import {getUsers,putUsers,postUsers,getUsersId,putUsersId,deleteUsers,getUsersRoles,putUsersIdRole} from '@/api/user'
import validator from "@/utils/validator"
export default {
 name:'userIndex',
 data() {
   return {
     input:'',
     paramData:{
        query:'',//查询参数
        pagenum:1,//当前页码
        pagesize:2//每页显示条数
     },
     total:0,
     userListData:[],//用户数据
     AddDialogVisible: false,//添加用户弹出窗
     addruleForm:{
        username:'',
        password:'',
        mobile:'',
        email:''
     },
    //  修改用户
    amenUsers:{

    },
     //rules绑定到el-form的rules属性
      rules: {
         username: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
          ],
           email: [
            { required: true, message: '请输入电子邮箱', trigger: 'blur' },
             { validator: validator.validateEmail, trigger:'blur'}
          ],
           mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator: validator.validatePhone, trigger:'blur'}
          ]
      },
      amendruleForm:false,//修改用户
     //amendruleForm绑定到el-form的rules属性
      amendrules: {
           email: [
            { required: true, message: '请输入电子邮箱', trigger: 'blur' },
             { validator: validator.validateEmail, trigger:'blur'}
          ],
           mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator: validator.validatePhone, trigger:'blur'}
          ]
      },
      allocateRolesVisible:false,//分配角色
      configInfo:{},
      assignRolesData:[],
      assignNewRoles:''
   }
 },
 created(){
   this.userList()
 },
 methods:{
  //  获取数据
   async userList(){
      const {data} = await getUsers(this.paramData);
      console.log(data, '获取数据')
      if(data.meta.status !== 200){
        return this.$message.error(data.meta.msg)
      }
      this.userListData = data.data.users;
      this.total = data.data.total;//总条数
   },
  //  修改用户状态
  async stateMonitor(userOpting){
    // console.log(userOpting, '修改用户状态')
    const uid = userOpting.id;
    const type = userOpting.mg_state;
    const {data} = await putUsers(uid,type)
    if(data.meta.status !== 200){
      return this.$message.error(data.meta.msg)
    }else{
      return this.$message.success(data.meta.msg)
    }
    console.log(data, '')
  },
  // 每条数据触发
  newSizeChange(newPageSize){
     this.paramData.pagesize=newPageSize;
    //  重新请求数据
    this.userList()
  },
  // 每页数据触发
  newCurrentChange(newPageNum){
      this.paramData.pagenum=newPageNum;
      // 重新请求数据
       this.userList()
  },
  // 点击按钮搜索
  clickSearchBtn(){
    this.userList();
  },
  // enter键触发
  OnChange(){
    this.userList();
  },
  // 清空输入框
  empty(){
    this.userList();
  },
  // 添加用户按钮
  addUsers(){
    this.AddDialogVisible = true;
  },
  // 重置
  resetForm(formName) {
        this.$refs.addruleForm.resetFields();
      },
      //添加用户数据请求接口
  async addUserList(){
    this.$refs.addruleRef.validate(async valid =>{
      console.log(valid, '')
      if(!valid)return
      const {data} = await postUsers(this.addruleForm);
      console.log(data, '')

      if(data.meta.status!==201){
         return this.$message.error(data.meta.msg)
      }
         this.$message.success(data.meta.msg);
         this.AddDialogVisible=false
        this.userList()
    })
  },
  // 修改用户
  async amendUsers(id){
    // console.log(id, '')
  this.amendruleForm=true
  const {data} = await getUsersId(id);
  this.amenUsers=data.data;
  // console.log(data, '')
  },
  // 修改用户数据提交
  amenUserList(){
    this.$refs.amendruleRef.validate(async vald=>{
       if(!vald) return
       const {data} = await putUsersId(this.amenUsers)
       if(data.meta.status!=200){
         return this.$message.error(data.meta.msg)
       }
        this.amendruleForm=false;
        this.userList()
        this.$message.success(data.meta.msg)
    //  console.log(data, '修改用户数据提交')
    })


  },
  // 删除单个用户
  async deleteUser(id){
    // MessageBox 弹框
     const res = await this.$confirm('此操作将永久删除该该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
   console.log(res, '')
   if(res !== 'confirm' ){
     this.$message.info('用户取消删除')
   }
  // 调用接口删除用户
      const {data} = await deleteUsers(id);
      if(data.meta.status !==200)return this.$message.error(data.meta.msg)
    this.$message.success(data.meta.msg)
    // 重新渲染数据
    this.userList()

  },
  // 分配角色
  async assignRoles(configInfo){
    this.configInfo = configInfo;
 let {data} =await getUsersRoles();
//  console.log(data, '分配角色')
 this.assignRolesData = data.data;
 console.log(this.assignRolesData, '')
 if(data.meta.status !==200)return this.$message.error(data.meta.msg);
    this.allocateRolesVisible=true
  },
  // 分配角色提交
  async selectOption(){
    if(!this.assignNewRoles)return this.$message.error('请选择分配角色！！！')
     let {data} = await putUsersIdRole(this.configInfo,this.assignNewRoles);
     console.log(data, '分配角色提交')
     if(data.meta.status !==200)return this.$message.error(data.meta.msg)
     this.allocateRolesVisible=false
     this.userList()
     this.$message.success(data.meta.msg)
  }
 }
}
</script>

<style lang="less" scoped>
 .userIndex{
   .paging{
     padding-top: 20px;
   }
 }
</style>
